package org.jbelis.yodaquotes.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jbelis.yodaquotes.Quote;
import org.jbelis.yodaquotes.store.QuoteStore;
import org.jbelis.yodaquotes.store.jdo.JDOQuoteStore;
import org.jbelis.yodaquotes.store.jdo.PMF;
import org.json.JSONWriter;

import java.util.Random;

public class GetRandomQuote extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4765264161544096861L;
	
	private Random rand = new Random();
	private QuoteStore store = new JDOQuoteStore();

	
	@Override
	public final void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		process(request, response);
	}

	@Override
	public final void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) 
	{
		Quote quote = getRandomQuote(request.getParameter("author"));

		try {
			quote.write(response.getWriter());
		} catch (Exception e) {

		}
	}

	public Quote getRandomQuote(String author) {

		List<Quote> quotes = store.findByAuthor(author);
		
		Quote quote = null;
		if (!quotes.isEmpty()) {
			quote = quotes.get(rand.nextInt(quotes.size()));
		}

		return quote;
	}
	
	
}
